package handler

import (
	"context"
	"log"

	pb "github.com/treelab/updatecolumn/protos"
)

// Server of column
type Server struct {
	pb.UnimplementedColumnServer
}

// Update implements updatecolumn.ColumnServer
func (s *Server) Update(ctx context.Context, in *pb.UpdateRequest) (*pb.UpdateResponse, error) {
	log.Printf("Server Received: requestID: %v, columnID %v", in.GetRequestID(), in.GetColumnID())

	///TODO ... 封装全局的错误code
	okResponse := &pb.UpdateResponse{Code: 400518000, Msg: "operation success"}

	failedResponse := &pb.UpdateResponse{Code: 400514000, Msg: "operation failed"}

	//0、取出要转换成目标列类型
	targetColumnType := in.GetColumnConfig().GetColumnType()

	log.Printf("User request change Column %v to %v", in.GetColumnID(), targetColumnType)

	//1、we validate Column Exist
	targetCol, ok := validateColumnExist(in.GetWorkspaceID(), in.GetCoreID(), in.GetTableID(), in.GetColumnID())

	if !ok {
		return failedResponse, nil
	}

	if targetColumnType == pb.ColumnType_Formula || targetColumnType == pb.ColumnType_RollUp {
		if targetCol.ColumnType == pb.ColumnType_name[int32(pb.ColumnType_Formula)] ||
			targetCol.ColumnType == pb.ColumnType_name[int32(pb.ColumnType_RollUp)] {
			//开转换到Formula和RollUp类型

		}

	}

	//3、GetColumnAllColumnObjByColumnIds 查出cell的所有依赖
	getAllreferencedColumnByColumnIds()

	//其他类型
	startToCovertColumn(in, targetColumnType)

	//4、updateColumnCellRelationships 更新列关系
	updateColumnCellRelationships()

	//6、updateFormView_V2
	updateFormView()

	okResponse.Msg = "Hello Client " + in.GetRequestID() + "In Column" + in.GetColumnID()
	return okResponse, nil

}
